package com.coder.shop.rpc.service.impl;

import java.util.Date;
import java.util.Random;

import javax.annotation.Resource;

import org.apache.commons.lang.time.DateUtils;

import com.coder.shop.dao.mapper.BaseMsgCodeMapper;
import com.coder.shop.dao.model.BaseMsgCode;
import com.coder.shop.mq.listener.MsgCodeSender;
import com.coder.shop.rpc.api.MsgCodeService;

public class MsgCodeServiceImpl implements MsgCodeService {
	
	@Resource
	private BaseMsgCodeMapper mapper;
	
	@Resource
	private MsgCodeSender msgCodeSender;

	@Override
	public void sendMsgCode(String phone) {
		
		//生成验证码
		int code = randCode();
		
		//验证码存放数据库
		BaseMsgCode msgCode = new BaseMsgCode();
		msgCode.setCode(code+"");
		msgCode.setPhone(phone);
		msgCode.setStatus(BaseMsgCode.STATUS_NO_USE);
		Date thruTime = DateUtils.addMinutes(new Date(), 10);
		msgCode.setThruTime(thruTime);
		mapper.insert(msgCode);
		
		//将验证码发送到MQ
		msgCodeSender.send(msgCode);
	}
	
	private int randCode() {
		Random random = new Random();
		return (int)(random.nextDouble() * 10000);
	}

	@Override
	public BaseMsgCode selectByCodeAndPhone(String phone, String code, int status) {
		return mapper.selectByCodeAndPhone(phone, code, status);
	}

}
